#coding=utf-8
"""
redis class
Author: kaspar
Date: 2022-04-09
"""
import threading
import redis
from util.config import Config
from util.logger import Logger
import util.common as common

class Bredis(object):
    """
    redis class
    """
    redis_instance = None
    redis_mutex = threading.Lock()
    def __init__(self):
        """
        init function
        """
        self._redis_host = Config.get_conf('redis', 'host')
        self._redis_port = int(Config.get_conf('redis', 'port'))
        self._redis_db = Config.get_conf('redis', 'db')
        self._redis_pwd = Config.get_conf('redis', 'pwd')
        self._redis_conn = None
        self._redis_max_retry = int(Config.get_conf('redis', 'retry'))
        self._connect_timeout = int(Config.get_conf('redis', 'connect_timeout'))

    @staticmethod
    def connect():
        """
        redis connent
        """
        Bredis.redis_instance._redis_conn = redis.Redis(\
            host=Bredis.redis_instance._redis_host,\
            port=Bredis.redis_instance._redis_port,\
            password= Bredis.redis_instance._redis_pwd,\
            db=Bredis.redis_instance._redis_db,\
            socket_connect_timeout=Bredis.redis_instance._connect_timeout)

    @staticmethod
    def check_connect_once():
        """
        check connect once
        """
        try:
            if Bredis.redis_instance._redis_conn is None:
                Bredis.connect()
            Bredis.redis_instance._redis_conn.ping()
            return 0
        except Exception as e:
            Logger.writelog("error", "redis connent reconnet error: %s"\
                % str(e))
            # redis reconnet
            Bredis.connect()
            return -1

    @staticmethod
    def check_connect():
        """
        reconnect
        """
        try_index = 0
        while try_index < Bredis.redis_instance._redis_max_retry:
            try_index += 1
            connent_flag = Bredis.check_connect_once()
            if 0 == connent_flag:
                return

    @staticmethod
    def get_instance():
        """
        get redis instance
        """
        if(Bredis.redis_instance is None):
            Bredis.redis_mutex.acquire()
            if(Bredis.redis_instance is None):
                Bredis.redis_instance = Bredis()
                Bredis.check_connect()
            Bredis.redis_mutex.release()
        else:
            # check reconnect
            Bredis.redis_mutex.acquire()
            Bredis.check_connect()
            Bredis.redis_mutex.release()
        return Bredis.redis_instance._redis_conn


class HandlerRedis(object):
    """
    redis handler
    """
    def __init__(self):
        self._redis = Bredis.get_instance()

    def set(self, key, value):
        res = self._redis.set(common.encode_key(key), value)
        self.set_expire(key)
        return res

    def set_expire(self, key):
        self._redis.expire(common.encode_key(key), int(Config.get_conf('server', 'ip_expire')))

    def ttl(self, key):
        return self._redis.ttl(common.encode_key(key))

    def get(self, key):
        return self._redis.get(common.encode_key(key))

    def delete(self, key):
        return self._redis.delete(common.encode_key(key)) == 1

    def exist(self, key):
        return self._redis.exists(common.encode_key(key)) == 1

if __name__ == '__main__':
    r = HandlerRedis()
    # print(r.set(common.encode_key(b'192.168.0.1'), 1))
    # print(int(r.get(common.encode_key(b'192.168.0.1'))))
    # print(r.exist('192.168.0.1'))
    print(r.delete('127.0.0.1'))
    # print(r.exist('192.168.0.1'))